package com.suray.wcs.service.pojo.rgv.rgv.protocol.message;

import com.suray.basic.wcs.utils.LoggerUtil;
import com.suray.basic.wcs.utils.typedef.Bit;
import com.suray.basic.wcs.utils.typedef.Byte;
import com.suray.basic.wcs.utils.typedef.Word;
import com.suray.commin.core.utils.SpringContextHolder;
import com.suray.commin.exception.OrderExecuteException;
import com.suray.wcs.service.pojo.Rgv;
import com.suray.wcs.service.pojo.rgv.rgv.protocol.base.RgvRecMessage;
import com.suray.wcs.service.pojo.rgv.rgv.protocol.util.RgvMessageType;
import com.suray.wcs.service.system.service.impl.CodeDBServiceImpl;

import java.io.IOException;

public class RgvClearOrderRecMessage extends RgvRecMessage {

    CodeDBServiceImpl codedbService = SpringContextHolder.getBean(CodeDBServiceImpl.class);

    public RgvClearOrderRecMessage(Rgv rgv) {
        super(rgv, "里程清除指令接收");

        baseDatas.add(new Word("头帧", "取值0x02FD"));
        baseDatas.add(new Byte("设备ID", "取值范围：0-255， 小车对应设备号"));
        baseDatas.add(new Byte("life", "心跳、指令、任务共用，没发一帧数据+1,0-255循环，res收到后原数据返回"));
        baseDatas.add(new Bit(4,"frameType", "报文类型"));
        baseDatas.add(new Bit(4,"version", "版本号"));
        baseDatas.add(new Word("结果", "0：成功，1.失败"));
        baseDatas.add(new Word("报文长度", "整条报文的长度"));
        baseDatas.add(new Word("校验位", "CRC（循环冗余校验；低位在前，高位在后），采用crc16_modbus"));
        baseDatas.add(new Word("尾帧", "0x3FC"));
    }

    public int getResult() {
        return getValue("执行结果");
    }

    @Override
    public boolean checkMessage(byte[] recData, RgvMessageType rgvMessageType, Integer sendLife) throws IOException {
        boolean result = super.checkMessage(recData, rgvMessageType, sendLife);

        if (result) {
            analyzeMessage();
        }

        return result;
    }

    private void analyzeMessage() {
        // 0. 接受成功 1. 接受失败
        int result = getResult();
        if (result == 0) {

        } else {
            LoggerUtil.warn("scada清除失败", this.getClass());
            throw new OrderExecuteException(getRgv().getRgvDB().getRgvNo(), getResult(), "scada清除失败");
        }
    }

    @Override
    public Integer getMessageLife() {
        return getValue("life");
    }

    @Override
    public Integer getMessageType() {
        return getValue("报文类型");
    }
}
